package com.hy.ratelimiting.limiting;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:
 * <p>
 * User:Mr.Du
 * Date:2024/4/29
 * Time:10:48
 */
@Slf4j
@Service
public class LeakyBucketRateLimiter {

    private long bucketSize = 10;
    private long leakyRate = 1;
    private long currentSize = 0;
    private long lastTime = System.currentTimeMillis();

    public LeakyBucketRateLimiter() {
    }

    public LeakyBucketRateLimiter(long bucketSize, long leakyRate, long currentSize, long lastTime) {
        this.bucketSize = bucketSize;
        this.leakyRate = leakyRate;
        this.currentSize = currentSize;
        this.lastTime = lastTime;
    }

    public synchronized boolean allowRequest() {
        long currentTime = System.currentTimeMillis();
        long deltaTime = currentTime - lastTime;
        currentSize = Math.max(0, currentSize - deltaTime * leakyRate);
        if (currentSize < bucketSize) {
            currentSize++;
            lastTime = currentTime;
            return true;
        }
        return false;
    }
}
